import BasicCanvas from "./BasicCanvas";

export class ScaleCanvas extends BasicCanvas {
  scaleStep = 50;

  constructor(canvas: HTMLCanvasElement, canvasConfig: CanvasConfig) {
    super(canvas, canvasConfig);
  }

  init() {
    super.init();
    this.ctx.translate(0, this.canvasConfig.height);
    this.ctx.scale(1, -1);
    this.ctx.translate(
      this.canvasConfig.margin.left,
      this.canvasConfig.margin.bottom
    );
  }
  draw() {
    this.drawScale();
    this.drawScaleText();
  }

  private drawScale() {
    const lineWidth = 0.3;
    const color = "#34495e";
    // 绘制标尺
    const width =
      this.canvasConfig.width -
      this.canvasConfig.margin.left -
      this.canvasConfig.margin.right;
    let y = 0;
    // 绘制横线
    while (
      y <=
      this.canvasConfig.height -
        this.canvasConfig.margin.bottom -
        this.canvasConfig.margin.top
    ) {
      super.drawLine([0, y], [width, y], lineWidth, color);
      y += this.scaleStep * this.canvasConfig.scale;
    }
    // 绘制纵线
    let x = 0;
    const height =
      this.canvasConfig.height -
      this.canvasConfig.margin.top -
      this.canvasConfig.margin.bottom;
    while (
      x <=
      this.canvasConfig.width -
        this.canvasConfig.margin.left -
        this.canvasConfig.margin.right
    ) {
      super.drawLine([x, 0], [x, height], lineWidth, color);
      x += this.scaleStep * this.canvasConfig.scale;
    }
  }

  private drawScaleText() {
    // 绘制横线文字
    let x = 0;
    while (
      x <=
      this.canvasConfig.width -
        this.canvasConfig.margin.left -
        this.canvasConfig.margin.right
    ) {
      this.ctx.save();
      this.ctx.translate(x, -10);
      const txt = ((x * 2) / this.canvasConfig.scale).toString();
      super.drawText(txt, [0, 0]);
      this.ctx.restore();
      x += this.scaleStep;
    }
    // 绘制纵线文字
    let y = 0;
    while (
      y <=
      this.canvasConfig.height -
        this.canvasConfig.margin.top -
        this.canvasConfig.margin.bottom
    ) {
      this.ctx.save();
      this.ctx.translate(-25, y);
      const txt = (
        y / 5 / this.canvasConfig.scale +
        this.canvasConfig.startY / 5
      ).toString();
      super.drawText(txt, [0, 0], "12px consolas", "right");
      this.ctx.restore();
      y += this.scaleStep;
    }
  }
}
